﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace SkinnedEffExample
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Model model;
        AnimationPlayer animationPlayer;
        Matrix view;
        Matrix proj;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            model = Content.Load<Model>("dude");
            
            SkinningData skinningData = model.Tag as SkinningData;
            if (skinningData == null)
            {
                throw new InvalidOperationException("This model does not contain a SkinningData tag.");
            }
            //create an animation player and start decoding an animation clip
            animationPlayer = new AnimationPlayer(skinningData);
            animationPlayer.StartClip(skinningData.AnimationClips["Take 001"]);
            proj = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 1.0f, 300.0f);
            view = Matrix.CreateLookAt(new Vector3(2, 45, -110), new Vector3(0, 35, 0), Vector3.Up);
            world = Matrix.CreateRotationY(MathHelper.ToRadians(180));
            origBoneTransform = model.Bones["Head"].Transform;
            transforms = new Matrix[model.Bones.Count];

            //update once to place figure
            //animationPlayer.Update(TimeSpan.Zero, true, Matrix.Identity);

            //foreach (ModelBone mm in model.Bones)
            //{
            //    Console.Out.WriteLine(mm.Name);
            //    foreach (ModelBone mmp in mm.Children)
            //    {
            //        Console.Out.WriteLine("--> " + mmp.Name);
            //    }
            //}
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        float rot = 0;
        Matrix rotation = Matrix.Identity;
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            //turn
            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                //set increment
                rot += 0.1f;
                //set delay of rotation
                if (rot < -1) { rot = -1; }
                rotation = Matrix.CreateRotationY(MathHelper.ToRadians(rot));
                world = rotation * world;
                //animationPlayer.Update(gameTime.ElapsedGameTime, true, rotation * Matrix.Identity);
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                //set increment
                rot -= 0.1f;
                //set delay of rotation
                if (rot > 1) { rot = 1; }
                rotation = Matrix.CreateRotationY(MathHelper.ToRadians(rot));
                world = rotation * world;
                //animationPlayer.Update(gameTime.ElapsedGameTime, true, rotation * Matrix.Identity);
            }

            //move forward
            //if (Keyboard.GetState().IsKeyDown(Keys.Up))
              //  foreach (ModelBone mb in model.Bones)
                //{
                  //  if mb.Name == 
                //}

                //animationPlayer.Update(gameTime.ElapsedGameTime, true, rotation * Matrix.Identity);
            //move backward
            //hur ska man få den att röra sig baklänges?
            //if (Keyboard.GetState().IsKeyDown(Keys.Down))
            //    animationPlayer.Update(gameTime.ElapsedGameTime, true, rotation * Matrix.Identity);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        BasicEffect be;
        Matrix[] transforms;
        Matrix world = Matrix.Identity;
        Matrix origBoneTransform;
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            //model.CopyAbsoluteBoneTransformsTo(transforms);
            transforms = animationPlayer.GetBoneTransforms();
            //transforms = animationPlayer.GetSkinTransforms();
            //model.Bones["Head"].Transform = Matrix.CreateScale(1.5f);//Matrix.CreateRotationY(-(float)Math.Sin((float)gameTime.TotalGameTime.TotalSeconds)) * origBoneTransform;


            foreach (ModelMesh mm in model.Meshes)
            {
                foreach (SkinnedEffect se in mm.Effects)
                {
                    se.EnableDefaultLighting();
                    se.Projection = proj;
                    se.View = view;
                    se.SetBoneTransforms(transforms);
                    //se.World = transforms[mm.ParentBone.Index] *world;
                    //se.CurrentTechnique.Passes[0].Apply();
                }
                mm.Draw();
            }
            //model.Draw(Matrix.Identity, be.View, be.Projection);
            
            //Matrix[] bones = animationPlayer.GetSkinTransforms();
            //foreach (ModelMesh mesh in model.Meshes)
            //{
            //    foreach (SkinnedEffect effect in mesh.Effects)
            //    {
            //        effect.SetBoneTransforms(bones);
            //        effect.View = view;
            //        effect.Projection = proj;
            //        effect.EnableDefaultLighting();
            //        effect.SpecularColor = Vector3.Zero;
            //    }
            //    mesh.Draw();
            //}

            base.Draw(gameTime);
        }
    }
}
